#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2022/11/17 12:21
# file: user_role.py
# author: lotus163
from typing import List, Optional

from ...models import SysUserRoleDb


class UserRoleService:

    async def add_role_by_user_id(self, userId: int, roleId: int):
        await SysUserRoleDb.create(userId=userId, roleId=roleId)

    async def add_role_by_user_ids(self, userIds: List[int], roleId: int):
        user_roles_dbs = []
        for user_id in userIds:
            user_roles_dbs.append(SysUserRoleDb(userId=user_id, roleId=roleId))
        await SysUserRoleDb.bulk_create(user_roles_dbs)

    async def add_roles_by_user_id(self, userId: int, roleIds: List[int]):
        user_roles_dbs = []
        for role_id in roleIds:
            user_roles_dbs.append(SysUserRoleDb(userId=userId, roleId=role_id))
        await SysUserRoleDb.bulk_create(user_roles_dbs)

    async def get_role_ids_by_user_id(self, userId: int) -> Optional[List[int]]:
        # 获取userId的角色列表
        user_role_dbs = await SysUserRoleDb.filter(userId=userId).all()
        role_ids = [user_role.roleId for user_role in user_role_dbs]
        return list(set(role_ids))

    async def delete_roles_by_user_id(self, userId: int):
        await SysUserRoleDb.filter(userId=userId).delete()

    async def update_roles_by_user_id(self, userId: int, roleIds: List[int]):
        # 先删除，再授权
        await self.delete_roles_by_user_id(userId)
        await self.add_roles_by_user_id(userId, roleIds)

    async def cancel_role_by_user_id(self, userId: int, roleId: int):
        await SysUserRoleDb.filter(userId=userId, roleId=roleId).delete()

    async def cancel_role_by_user_ids(self, userIds: List[int], roleId: int):
        await SysUserRoleDb.filter(userId__in=userIds, roleId=roleId).delete()

    async def get_user_ids_by_role_id(self, roleId: int) -> List[int]:
        """根据角色查询用户ids"""
        user_role_dbs = await SysUserRoleDb.filter(roleId=roleId).all()
        user_ids_temp = []
        for user_role_db in user_role_dbs:
            user_ids_temp.append(user_role_db.userId)
        return list(set(user_ids_temp))
